// 转场插件 - 根据路由类型自动选择转场效果
import type { App } from 'vue'
import type { Router } from 'vue-router'

export interface TransitionConfig {
  name: string
  mode: 'out-in' | 'in-out' | undefined
  duration: number
}

// 转场效果配置
const TRANSITIONS = {
  FORWARD: { name: 'stepin-transition', mode: undefined, duration: 400 },
  BACKWARD: { name: 'stepin-reverse-transition', mode: undefined, duration: 400 },
  NONE: { name: '', mode: undefined, duration: 0 }
}

// 检测路由前进/后退状态
let isBackward = false

export function getRouteTransition(routePath?: string): TransitionConfig {
  // 管理员路由不使用过渡动画
  if (routePath && routePath.startsWith('/admin')) {
    return TRANSITIONS.NONE
  }
  
  // 用户中心路由不使用全局过渡动画（使用局部动画）
  if (routePath && routePath.startsWith('/user')) {
    return TRANSITIONS.NONE
  }
  
  // 根据前进/后退状态返回不同的转场效果
  return isBackward ? TRANSITIONS.BACKWARD : TRANSITIONS.FORWARD
}

export function setBackwardState(backward: boolean): void {
  isBackward = backward
}

export default {
  install(app: App, router: Router) {
    app.config.globalProperties.$currentTransition = TRANSITIONS.FORWARD
    
    // 监听浏览器的前进/后退操作
    if (typeof window !== 'undefined') {
      let isPopState = false
      
      window.addEventListener('popstate', () => {
        isPopState = true
        // 延迟重置，确保router.beforeEach能检测到
        setTimeout(() => {
          isPopState = false
        }, 100)
      })
      
      router.beforeEach((to, from, next) => {
        // 如果检测到popstate事件，说明是后退/前进操作
        isBackward = isPopState
        
        const transition = getRouteTransition(to.path)
        app.config.globalProperties.$currentTransition = transition
        next()
      })
    }
    
    app.config.globalProperties.$getTransition = getRouteTransition
    app.config.globalProperties.$setTransition = (name: string) => {
      const transition = Object.values(TRANSITIONS).find(t => t.name === name)
      if (transition) {
        app.config.globalProperties.$currentTransition = transition
      }
    }
    app.config.globalProperties.$setBackwardState = setBackwardState
  }
}

export { TRANSITIONS }
